import GameService from "./GameService";
import Handler from "./Handler";
import NativeUtils from "./NativeUtils";

const { ccclass, property } = cc._decorator;

export var AdType = {
    OPEN_SCREEN: 1,
    NATIVE: 2,
    INTERSTITIAL: 3,
    BANNER: 4,
    MOTIVATIONAL_VIDEO: 5
}
export interface IAdConfig {
    "adId": number,
    "adType": number,
    "adPlacement": number[],
    "oneDayDisplay": number,
    "fullScreen": boolean,
    "productType": number,
    "interstitialType"?: number,
    "autoSkipTime"?: number,
    "countdownDuration"?: number,
    "closePageDelayInterval"?: number,
}

export var adPosType = {
    "PandaTravel": 1,
    "MatchGameTargetPage": 2,
    "MatchGameMoneyPage": 3,
    "MatchGameView": 4,
    "MatchGameSuccessJJPage": 5,
    "MatchGameFailPage": 6,
    "MatchGameAddPropPage": 7,
    "MatchGameSetPage": 8,
    "ClickEveryDayPage": 9

}

@ccclass
export default class AdManager {

    private static adConfig: IAdConfig[] = [];
    public static yardLevelExchangeRates: {
        minValue: number,
        maxValue: number,
        nextWithdrawRate: number,
        stage: number
    }[] = [];


    static _instance: AdManager;
    static getInstance(): AdManager {
        if (!AdManager._instance) {
            AdManager._instance = new AdManager();
        }
        return AdManager._instance;
    }

    playNormalVideoAd(cb, fail, posId = 7) {
        NativeUtils.showVideoAd(posId, cb);
    }

    private static extractReturnInfo = null;

    private static tryTime = 0;
    private static adConfigPromise = null;

    static getAdConfig() {
        if(cc.sys.isBrowser){
           return new Promise((resolve) => {
            this.adConfig = [{"productType":2102,"adType":3,"adPlacement":[1,4,6,8,9],"adId":2845,"oneDayDisplay":200,"fullScreen":false,},{"productType":2102,"adType":5,"adPlacement":[6,7,9],"adId":2847,"oneDayDisplay":200,"fullScreen":false},{"productType":2102,"adType":2,"adPlacement":[2,3,6,7,8,9],"adId":2848,"oneDayDisplay":200,"fullScreen":false}]
            resolve(this.adConfig);
           })
            return;
        }
        if (this.adConfigPromise) {
            return this.adConfigPromise; // Return the existing promise
        }

        this.adConfigPromise = new Promise((resolve) => {
            if (this.adConfig && this.adConfig.length) {
                resolve(this.adConfig); // Resolve with existing ad configuration
                return;
            }

            if (this.tryTime >= 3) {
                console.error("Failed to fetch ad configuration");
                resolve([]); // Resolve with an empty array if max retries reached
                return;
            }

            this.tryTime++;

            GameService.adConfig(
                Handler.create(this, (t) => {
                    this.adConfig = t.adConfigs;
                    NativeUtils.setSplashAdId();
                    resolve(this.adConfig);
                }),
                Handler.create(this, (e) => {
                    console.error("Failed to fetch ad configuration", e);
                    resolve([]); // Resolve with an empty array in case of error
                })
            );
        });

        // Clear the promise after it resolves or rejects
        this.adConfigPromise.finally(() => {
            this.adConfigPromise = null;
        });

        return this.adConfigPromise;
    }

    static async getAdIDByPlace(place, type: number) {
        if (place['posName']) {
            place = place['posName']
        }
        return new Promise((resolve) => {
            AdManager.getAdConfig().then((adConfigs: IAdConfig[]) => {

                const adId = adConfigs.filter((data) => {
                    return data.adPlacement.indexOf(place) != -1 && data.adType == type;
                })[0]?.adId;
                console.log(`请求广告位置${place},id:${adId}`);
                resolve(adId || 0);
            });
        })
    }

    static async getAdTypeByPlace(place) {
        return new Promise((resolve) => {
            AdManager.getAdConfig().then((adConfigs: IAdConfig[]) => {
                const adType = adConfigs.filter((data) => {
                    return data.adPlacement.indexOf(place) != -1;
                })[0]?.adType;
                resolve(adType || '');
            });
        })
    }

    static async getAdIDByType(type) {
        return new Promise((resolve) => {
            AdManager.getAdConfig().then((adConfigs: IAdConfig[]) => {
                const adId = adConfigs.filter((data) => {
                    return data.adType == type;
                })[0]?.adId;
                resolve(adId || '');
            });
        })
    }

    static async getConfigByAID(aid) {
        return new Promise((resolve) => {
            AdManager.getAdConfig().then((adConfigs: IAdConfig[]) => {
                const config: IAdConfig = adConfigs.filter((data) => {
                    return data.adId == aid;
                })[0];
                resolve(config || '');
            });
        })
    }

}


